<template>
  <div>
    <sticky :offset="0">
      <x-header style="background-color:#000;">报修登记</x-header>
    </sticky>
    <!-- <blur :blur-amount="40" :url="blururl" :height="78">
      <flexbox>
        <flexbox-item>
          <div class="center">
            <x-icon type="ios-arrow-thin-left"></x-icon>
          </div>
        </flexbox-item>
        <flexbox-item>
          <div class="center">报修登记</div>
        </flexbox-item>
        <flexbox-item></flexbox-item>
      </flexbox>
    </blur> -->

    <group>
      <search @result-click="mapResultClick" @on-submit="onMapSubmit" @on-cancel="onMapCancel" @on-change="getMapResult" :results="mapResult"
        v-model="form.building" placeholder="小区/写字楼/地址" position="absolute" ref="mapSearch"></search>
      <x-input :min="1" :max="100" label-width="6em" ref="doornumber" v-model="form.addressDetail" :title='`<span style="red">门牌号</span>`'
        placeholder="门牌号" required></x-input>
      <x-input :min="1" :max="80" label-width="6em" ref="uname" v-model="form.username" :title='`<span style="red">业主名</span>`'
        placeholder="姓名" required></x-input>
      <popup-picker title="服务种类" :data="stype" :columns="2" v-model="form.kind" show-name></popup-picker>
      <x-textarea title="报修说明" ref="aDetail" :max="200" :show-counter="true" v-model="form.remark" required :rows="1"></x-textarea>
      <!-- <BMap ref="baidumap" v-on:changecart="changecart"></BMap> -->
    </group>

    <group label-width="5em" title="现场照片" v-show="isPhoto" @click.stop="addPic">
      <cell-box>
        <div class="image-list">
          <div class="list-default-img" v-show="isPhoto" @click.stop="addPic">
            <img src="http://placeholder.qiniudn.com/640x300" width="210" height="100" />
            <span>请拍照上传照片</span>
            <input type="file" accept="image/*" @change="onFileChange" ref="file" style="display: none;">
          </div>
        </div>
      </cell-box>
    </group>

    <group>
      <cell-box v-show="!isPhoto">
        <div class="image-list">
          <ul class="list-ul" v-show="!isPhoto">
            <li class="list-li" v-for="(iu, index) in imgUrls">
              <a class="list-link" @click='previewImage(iu)'>
                <span>现场照片</span>
                <badge text="x" class="delete" @click.native.stop="delImage"></badge>
                <img :src="iu" width="110" height="50">
              </a>
            </li>
          </ul>
        </div>

        <div class="add-preview" v-show="isPreview" @click="closePreview">
          <img :src="previewImg" width="200">
        </div>
      </cell-box>
    </group>
    <flexbox>
      <flexbox-item></flexbox-item>
      <flexbox-item>
        <!-- <x-button action-type="button" :disabled="upBtnDis" type="primary" @click.native="saveImage">提交报修</x-button> -->
        <x-button action-type="button" type="primary" @click.native="saveImage">提交报修</x-button>
      </flexbox-item>
      <flexbox-item></flexbox-item>
    </flexbox>
    <toast v-model="showTips" position="bottom" type="text" width="20em">{{tipsContent}}</toast>

    <!-- <tabs :tabtype="0"></tabs> -->
  </div>
</template>

<script>
  import {
    Blur,
    Sticky,
    XTextarea,
    Card,
    CellBox,
    Search,
    PopupPicker,
    Flexbox,
    FlexboxItem,
    Badge,
    XInput,
    Group,
    Cell,
    XHeader,
    Toast,
    XButton,
    Tab,
    TabItem
  } from "vux"

  // import BMap from "../../components/BaiduMapResult.vue"
  import tabs from "../../components/footer"
  import {
    getTree,
    getList
  } from '../../api/serviceType'
  import lrz from "lrz"
  import {
    getLocationNearby
  } from "@/api/map"
  import {
    regworkorder
  } from "@/api/workorder"

  import util from "@/utils/"

  export default {
    components: {
      Blur,
      Sticky,
      XTextarea,
      Card,
      CellBox,
      Search,
      PopupPicker,
      Flexbox,
      FlexboxItem,
      Badge,
      XInput,
      Group,
      Cell,
      XHeader,
      Toast,
      XButton,
      Tab,
      TabItem,
      tabs,
      //BMap
    },
    data() {
      return {
        blururl: "https://static.vux.li/demo/2.jpg",
        stype: [],
        imgUrls: [],
        urlArr: [],
        value3: [],
        mapResult: [],
        listQuery: {
          PageIndex: 1,
          PageSize: 500,
        },
        form: {
          username: "",
          pic: "",
          building: "",
          addressDetail: "",
          remark: "",
          kind: [],
          STID: 0,
          mobile: ""
        },
        keyword: '',
        isPhoto: true,
        btnTitle: "",
        isModify: false,
        previewImg: "",
        isPreview: false,
        upBtnDis: false,
        tipsContent: "",
        showTips: false
      };
    },
    created() {
      // let shc = ChinaAddressV4Data;
      // shc.forEach(x => {
      //   if (x.value == "310000" || x.parent == "310000" || x.parent == "310100")
      //     this.addressSHCData.push(x);
      // })
      this.fetchTree()
    },
    watch: {
      imgUrls: "toggleAddPic",
    },
    methods: {
      afterMapProcess() {
        this.mapResult = []
        this.$refs.aDetail.focus()
      },
      onMapCancel() {
        this.form.building = ""
        this.afterMapProcess()
      },
      mapResultClick(item) {
        // console.log(item)
        this.form.building = item.title
        this.afterMapProcess()
      },
      onMapSubmit() {
        this.$refs.mapSearch.setBlur()
        this.afterMapProcess()
      },
      getMapResult(val) {
        let jsonp = require('jsonp')
        let res = []
        jsonp('http://api.map.baidu.com/place/v2/search?region=上海&output=json&ak=' + util.ak + '&query=' + val + '',
          null,
          function (err, data) {
            if (err) {
              console.error(err.message)
            } else {
              if (data.status == 0) {
                if (data.results) {
                  data.results.forEach(x => {
                    res.push({
                      title: x.name + ',' + x.address
                    })
                  })
                }
              } else {
                // this.mapResult = []
              }
            }
          })
        if (res) {
          this.mapResult = res
        } else {
          this.mapResult = []
        }
        // console.log(val)
      },
      fetchTree() {
        getList(this.listQuery).then(response => {
          this.treelist = response.data.data.serviceTypeListView
          if (this.treelist) {
            this.treelist.forEach(x => {
              if (x.stIsDelete == "0") {
                this.stype.push({
                  name: x.stName,
                  value: x.stid.toString(),
                  parent: x.sT_UpperID.toString()
                })
              }
            })
          }
        })
      },
      toggleAddPic: function () {
        let vm = this;
        if (vm.imgUrls.length >= 1) {
          vm.isPhoto = false;
        } else {
          vm.isPhoto = true;
        }
      },
      addPic: function (e) {
        // console.log(e)
        let vm = this;
        this.$refs.file.click()
        // $("input[type=file]").trigger("click");
        return false;
      },
      onFileChange: function (e) {
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length) return;
        this.createImage(files, e);
      },
      createImage: function (file, e) {
        let vm = this;
        lrz(file[0], {
            width: 480
          })
          .then(function (rst) {
            vm.imgUrls.push(rst.base64);
            console.log(rst);
            return rst;
          })
          .always(function () {
            // 清空文件上传控件的值
            e.target.value = null;
          });
        this.upBtnDis = false;
      },
      delImage: function (index) {
        let vm = this;
        // let btnArray = ["取消", "确定"];
        // mui.confirm("确定删除该图片?", "提示", btnArray, function(e) {
        //   if (e.index == 1) {
        //     vm.imgUrls.splice(index, 1);
        //   }
        // });
        this.tipsContent = "完成删除";
        this.showTips = true;
        vm.imgUrls.splice(index, 1);
        this.upBtnDis = true;
      },
      previewImage: function (url) {
        let vm = this;
        vm.isPreview = true;
        vm.previewImg = url;
      },
      closePreview: function () {
        let vm = this;
        vm.isPreview = false;
        vm.previewImg = "";
      },
      saveImage: function () {
        let vm = this;
        let urlArr = [],
          imgUrls = this.imgUrls;

        for (let i = 0; i < imgUrls.length; i++) {
          if (imgUrls[i].indexOf("file") == -1) {
            urlArr.push(imgUrls[i].split(",")[1]);
          } else {
            urlArr.push(imgUrls[i]);
          }
        }
        if (urlArr.length > 0) {
          this.form.pic = this.imgUrls.slice(0, 1).toString()
          // console.log(this.form.pic)
        }
        let flag = false
        if (this.$refs.doornumber.valid && this.$refs.uname.valid) {
          // console.log(this.form)
          if (this.form.addressDetail.length > 0 && this.form.username.length > 0 && this.form.kind.length > 0 &&
            this.form.building.length >
            0) {
            flag = true
          }
        }

        if (!flag) {
          this.tipsContent = "请完整输入报修信息"
          this.showTips = true
        } else {
          this.form.STID = this.form.kind.slice(1, 2).toString()
          console.log(this.form)

          // console.log(this.form.kind.slice(1, 2))
          regworkorder(this.form.username, this.form.pic, this.form.building, this.form.addressDetail,
            this.form.remark, this.form.STID).then(response => {
            console.log(response)
            console.log(response.data.returnObject)
          });
        }
      }
    }
  };

</script>

<style lang="scss">
  @import "../../style/common";

  body {
    background-color: #fff;
  }

  .center {
    text-align: center;
    padding-top: 20px;
    color: #fff;
    font-size: 18px;
  }

  .left {
    text-align: left;
    padding-top: 20px;
    color: #fff;
    font-size: 18px;
  }

  .delete {
    float: right;
  }

</style>
